import React, { useState, useEffect, useCallback } from 'react';
import TinderCard from 'react-tinder-card';
import { fetchPhotos, likePhoto } from '../store/photoStore';
import { throttle, debounce } from 'lodash';

const SwipeCard = () => {
  const [photos, setPhotos] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(true); // 添加加载状态

  useEffect(() => {
    loadPhotos();
  }, []);

  const loadPhotos = async () => {
    setIsLoading(true); // 开始加载
    const newPhotos = await fetchPhotos();
    console.log('Fetched Photos:', newPhotos);
    if (Array.isArray(newPhotos) && newPhotos.length > 0) {
      setPhotos((prevPhotos) => [...prevPhotos, ...newPhotos]);
    }
    setIsLoading(false); // 加载完成
  };

  // 规范化照片数据，确保兼容字符串或对象格式
  const normalizePhoto = (photo) => (typeof photo === 'string' ? photo : photo?.url);

  const handleSwipe = useCallback(
    throttle((direction) => {
      console.log('Swiped:', direction);
      if (currentIndex >= photos.length) return; // 防止越界
      if (direction === 'right') {
        likePhoto(photos[currentIndex]);
      }
      setCurrentIndex((prevIndex) => prevIndex + 1);
      if (currentIndex + 1 >= photos.length || photos.length <= 2) {
        loadPhotos();
      }
    }, 1000),
    [currentIndex, photos]
  );

  const handleLeftSwipe = useCallback(debounce(() => handleSwipe('left'), 300), []);
  const handleRightSwipe = useCallback(debounce(() => handleSwipe('right'), 300), []);

  return (
    <div
      className="swipe-card-container"
      style={{
        height: '90vh',
        width: '100%',
        position: 'relative',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        overflow: 'hidden',
      }}
    >
      {isLoading ? (
        <p>加载中...</p>
      ) : photos.length > 0 && currentIndex < photos.length ? (
        <TinderCard
          key={normalizePhoto(photos[currentIndex]) || `photo-${currentIndex}`} // 确保 key 唯一
          onSwipe={(dir) => handleSwipe(dir)}
          preventSwipe={['up', 'down']}
          style={{ flex: '0 0 auto', margin: '0' }}
        >
          <div
            className="swipe-card"
            style={{
              height: '80vh',
              width: '100%',
              borderRadius: '10px',
              boxShadow: '0 4px 10px rgba(0,0,0,0.2)',
              overflow: 'hidden',
            }}
          >
            <img
              src={normalizePhoto(photos[currentIndex])}
              alt="Swipe Card"
              style={{
                height: '100%',
                width: '100%',
                objectFit: 'cover',
                borderRadius: '10px',
              }}
            />
          </div>
        </TinderCard>
      ) : (
        <p>暂无图片</p>
      )}

      {/* 喜欢和不喜欢的按钮 */}
      <div
        className="swipe-buttons"
        style={{
          position: 'absolute',
          bottom: '20px',
          left: '50%',
          transform: 'translateX(-50%)',
          display: 'flex',
          justifyContent: 'space-between',
          width: '80%',
        }}
      >
        <button
          onClick={handleLeftSwipe}
          style={{
            flex: 1,
            marginRight: '10px',
            padding: '12px',
            background: 'linear-gradient(135deg, #ff5f6d, #ffc371)',
            color: 'white',
            border: 'none',
            borderRadius: '25px',
            cursor: 'pointer',
            fontSize: '16px',
            fontWeight: 'bold',
            boxShadow: '0 4px 10px rgba(0, 0, 0, 0.2)',
            transition: 'transform 0.2s, box-shadow 0.2s',
          }}
          onMouseOver={(e) => {
            e.target.style.transform = 'scale(1.05)';
            e.target.style.boxShadow = '0 6px 12px rgba(0, 0, 0, 0.3)';
          }}
          onMouseOut={(e) => {
            e.target.style.transform = 'scale(1)';
            e.target.style.boxShadow = '0 4px 10px rgba(0, 0, 0, 0.2)';
          }}
        >
          ❌ 左滑 (反感)
        </button>

        <button
          onClick={handleRightSwipe}
          style={{
            flex: 1,
            marginLeft: '10px',
            padding: '12px',
            background: 'linear-gradient(135deg, #56ab2f, #a8e063)',
            color: 'white',
            border: 'none',
            borderRadius: '25px',
            cursor: 'pointer',
            fontSize: '16px',
            fontWeight: 'bold',
            boxShadow: '0 4px 10px rgba(0, 0, 0, 0.2)',
            transition: 'transform 0.2s, box-shadow 0.2s',
          }}
          onMouseOver={(e) => {
            e.target.style.transform = 'scale(1.05)';
            e.target.style.boxShadow = '0 6px 12px rgba(0, 0, 0, 0.3)';
          }}
          onMouseOut={(e) => {
            e.target.style.transform = 'scale(1)';
            e.target.style.boxShadow = '0 4px 10px rgba(0, 0, 0, 0.2)';
          }}
        >
          ✅ 右滑 (倾慕)
        </button>
      </div>
    </div>
  );
};

export default SwipeCard;